package com.example.a2306_shop.fg

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.a2306_shop.MainActivity
import com.example.a2306_shop.R
import com.example.a2306_shop.adapter.CartAdapter
import com.example.a2306_shop.databinding.FragmentCartBinding
import com.example.lib_base.entity.Cart
import com.example.lib_base.mvvm.BaseFragment
import com.example.lib_base.param.CreateOrder
import com.example.lib_base.param.OrderDetail
import kotlin.math.log


class CartFragment : BaseFragment<FragmentCartBinding,CartViewModel>() {
    lateinit var cartAdapter: CartAdapter
    val list = mutableListOf<Cart>()
    override fun initData() {
        viewModel.cartSuccess.observe(this){
            if(it.code==200){
                cartAdapter.data.clear()
                cartAdapter.data.addAll(it.data.list)
                cartAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.updateSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.deleteSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.createSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                val tvMoney = binding.tvMoney.text.toString()
                //创建成功，需要跳转到支付界面
                var ids = arrayOf<Int>()
                list.forEach {
                    ids+=it.id
                }
                viewModel.delete(ids)
                cartAdapter.data.removeAll(list)
                cartAdapter.notifyDataSetChanged()
                checkBottom()
                list.clear()
                //先删除购物车数据
                //Log.d("sss", "initData: ${it.data.orderNo}")
                ARouter.getInstance().build("/app/PayActivity").withString("orderNo",it.data.orderNo).withString("amount",tvMoney).navigation()
            }
        }
    }

    override fun initView() {
        //初始化
        cartAdapter = CartAdapter()
        binding.rvCart.adapter = cartAdapter
        binding.rvCart.layoutManager = LinearLayoutManager(context)

        viewModel.cart("true","10","1")
        //点击item上的cb + —
        cartAdapter.addChildClickViewIds(R.id.cart_cb,R.id.cart_sub,R.id.cart_add)
        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.cart_cb->{
                    //页面上的选中状态发生变化(不需要我们进行代码处理)  adapter.data中的值也要发生变化   不需要调用接口
                    cartAdapter.data[position].isChecked = !cartAdapter.data[position].isChecked
                }
                R.id.cart_sub->{
                    //页面上的数据发生变化   adapter.data中的值也要发生变化  需要调用接口  当数量为1时，提示不能再减少了
                    if(cartAdapter.data[position].cartNum==1){
                        ToastUtils.showLong("不能再减少了")
                    }else{
                        cartAdapter.data[position].cartNum--
                        (cartAdapter.getViewByPosition(position,R.id.cart_num) as TextView).text = cartAdapter.data[position].cartNum.toString()
                        //调用接口
                        viewModel.update(cartAdapter.data[position].id,cartAdapter.data[position].cartNum)
                    }
                }
                R.id.cart_add->{
                    //页面上的数据发生变化   adapter.data中的值也要发生变化  需要调用接口
                    cartAdapter.data[position].cartNum++
                    (cartAdapter.getViewByPosition(position,R.id.cart_num) as TextView).text = cartAdapter.data[position].cartNum.toString()
                    //调用接口
                    viewModel.update(cartAdapter.data[position].id,cartAdapter.data[position].cartNum)
                }
            }
            //无论点击的是这三个中的哪个控件 都有可能会影响底部的全选或者金额
            checkBottom()
        }
        //点击底部全选 上方数据选中状态发生变化
        binding.cb.setOnCheckedChangeListener { buttonView, isChecked ->
            binding.cb.setOnClickListener {
                cartAdapter.data.forEach {
                    it.isChecked = isChecked
                }
                cartAdapter.notifyDataSetChanged()
                checkBottom()//注意也需要更新底部选中数量和金额
            }

        }

        //左滑删除
        ItemTouchHelper(object :ItemTouchHelper.Callback(){
            override fun getMovementFlags(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder
            ): Int {
                val left = ItemTouchHelper.LEFT
                return makeMovementFlags(0,left)
            }

            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return true
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                //删除当前item
                val position = viewHolder.layoutPosition
                //调用接口
                viewModel.delete(arrayOf(cartAdapter.data[position].id))
                //删除页面数据
                cartAdapter.data.removeAt(position)
                cartAdapter.notifyItemRemoved(position)//局部刷新
                //检查 底部选中状态
                checkBottom()
            }

        }).attachToRecyclerView(binding.rvCart)

        //点击管理  文字变成取消  底部显示  收藏和删除按钮   合计金额和立即下单隐藏
        binding.tvManage.setOnClickListener {
            if(binding.tvManage.text.toString()=="管理"){
                binding.tvManage.text = "取消"
                binding.llCancel.isVisible = true
                binding.llManage.isVisible = false
            }else{
                binding.tvManage.text = "管理"
                binding.llCancel.isVisible = false
                binding.llManage.isVisible = true
            }
        }
        //点击删除按钮 ，实现批量删除
        binding.btnDelete.setOnClickListener {
            //判断是否有选中的   有选中，进行删除   没有选中的，提示
            val cartList = cartAdapter.data.filter { it.isChecked }
            if(cartList.size>0){
                //有选中的
                var ids = arrayOf<Int>()
                cartList.forEach {
                    ids +=it.id
                }
                //调用接口
                viewModel.delete(ids)
                //局部更新页面
                cartAdapter.data.removeAll(cartList)//移除所有选中的购物车列表数据
                cartAdapter.notifyDataSetChanged()
                //影响底部数据
                checkBottom()
            }else{
                ToastUtils.showLong("至少选择一种商品")
            }
        }
        //点击立即下单按钮，调用创建订单接口
        binding.btnOrdernow.setOnClickListener {
            //先判断是否有选中的
            val filter = cartAdapter.data.filter { it.isChecked }
            if(filter.size>0){
                //调用创建订单接口
                val createOrder = CreateOrder()
                //地址id 支付方式  在创建参数时已经进行了正确的赋值 不需要重新给值了
                //将正确选中的商品添加到集合中即可
                val orderDetails = mutableListOf<OrderDetail>()
                filter.forEach {
                    val orderDetail = OrderDetail()
                    orderDetail.attrValueId = it.attrId
                    orderDetail.productId = it.productId
                    orderDetail.productNum = it.cartNum
                    orderDetails.add(orderDetail)
                }
                createOrder.orderDetails = orderDetails
                viewModel.orderCreate(createOrder)
                list.addAll(filter)
            }else{
                ToastUtils.showLong("请至少选择一种商品")
            }

        }

    }

    private fun checkBottom() {
        //判断是否选中  获取选中的列表数量
        val size = cartAdapter.data.filter { it.isChecked }.size
        binding.cb.text = "全选($size)"
        //和商品列表数量进行比较  如果相同  选中   不同  未选中
        if(size==cartAdapter.data.size&&cartAdapter.data.size>0){
            binding.cb.isChecked=true
        }else{
            binding.cb.isChecked=false
        }
        //合计金额
        var amount = 0f
        cartAdapter.data.filter { it.isChecked }
            .forEach {
                amount+=it.cartNum*it.price.toFloat()
            }
        binding.tvMoney.text = "合计:${amount}元"
        var count = 0
        cartAdapter.data.forEach {
            count+=it.cartNum
        }
        //获取上级控件
        val bottom = (activity as MainActivity).bottom
        bottom.getOrCreateBadge(R.id.cartFragment).number = count

    }

    override fun getViewModel(): Class<CartViewModel> = CartViewModel::class.java

    override fun getLayout(): Int  = R.layout.fragment_cart

}